/*
https://leetcode.cn/problems/shortest-common-supersequence/solution/xun-zhao-zui-chang-gong-gong-zi-xu-lie-h-qssq/
 */
public class Solution1092 {
    public String shortestCommonSupersequence(String str1, String str2) {
        int[][] f=new int[str1.length()+1][str2.length()+1];
        for (int i=1;i<=str1.length();i++){
            for (int j=1;j<=str2.length();j++){
                if (str1.charAt(i-1)==str2.charAt(j-1)){
                    f[i][j]=f[i-1][j-1]+1;
                }else{
                    f[i][j]=Math.max(f[i][j-1],f[i-1][j]);
                }
            }
        }
        int i=str1.length()-1,j=str2.length()-1;
        StringBuilder stringBuilder=new StringBuilder();
        while (i>=0 || j>=0){
            if (i<0){
                stringBuilder.append(str2.charAt(j));
                j--;
            }else if (j<0){
                stringBuilder.append(str1.charAt(i));
                i--;
            }else if (str1.charAt(i)==str2.charAt(j)){
                stringBuilder.append(str1.charAt(i));
                i--;
                j--;
            }else if (f[i][j+1]>f[i+1][j]){
                stringBuilder.append(str1.charAt(i));
                i--;
            }else{
                stringBuilder.append(str2.charAt(j));
                j--;
            }
        }
        return stringBuilder.reverse().toString();
    }

    public static void main(String[] args) {
        System.out.println(new Solution1092().shortestCommonSupersequence("abac","cab"));
    }
}
